import Axios from "axios";
import * as utils from "./utils";
import { Message } from "element-ui";

const $http = Axios.create();

// Before request 拦截器
$http.interceptors.request.use(
  config => {
    config.url = utils.getApiUrl(config.url);
    if (config.method === "post") {
      const querystring = require("querystring");
      config.data = querystring.stringify(config.data);
      // console.log(config.data);
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// After request
$http.interceptors.response.use(response => {
  response = response.data;
  if (response.res === "40000") {
    // response.msg !== '' && alert(response.msg);
    return response;
  } else if (response.res === "40003") {
    // TODO: 登录超时
    $router.replace();
    return new Promise(() => {});
  } else if (response.res !== "40000" && response.res !== "40003") {
    Message.error(response.msg);
  } else {
    Message.error(response.msg);
  }
});
export default $http;
